function throttle(fn, delay) {
  let now = 0
  let lastExec = 0
  let timer = null
  let context

  const execute = (args) => {
    fn.apply(context, args)
    lastExec = now
  }

  return (...args) => {
    context = this

    now = Date.now()

    if (timer) {
      clearTimeout(timer)
      timer = null
    }

    if (lastExec) {
      const diff = delay - (now - lastExec)
      if (diff < 0) {
        execute(args)
      } else {
        timer = setTimeout(() => {
          execute(args)
        }, diff)
      }
    } else {
      execute(args)
    }
  }
}

export default throttle
